<!-- 
    代码来自mikaisa
    Gitee: @mikaisazzz
    原创不易，使用请注明出处
 -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html,
        body {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        canvas {
            border: 2px solid black;
        }
    </style>
</head>

<body>
    <canvas width="1000" height="600"></canvas>
    <script>
        let canvas = document.querySelector('canvas')
        let ctx = canvas.getContext('2d')

        // 定义一个全局变量isPainting，如果鼠标按下则代表绘画开始，就把这个变量置为true。当鼠标抬起则代表绘画结束，置为false。加这一步的原因是因为mousemove这个事件的触发是不需要鼠标点击的，只需要鼠标在上面滑动就行，我们这样做是为了规避这个问题
        let isPainting = false

        canvas.onmousedown = (event) => {
            event.stopPropagation()
            isPainting = true
            ctx.beginPath()
            ctx.lineCap = 'round'
            ctx.strokeStyle = 'red'
            ctx.lineWidth = 2
            ctx.moveTo(event.offsetX, event.offsetY)
        }

        canvas.onmousemove = (event) => {
            event.stopPropagation()
            if (isPainting) {
                ctx.lineTo(event.offsetX, event.offsetY)
                ctx.stroke()
            }
        }

        canvas.onmouseup = (event) => {
            event.stopPropagation()
            isPainting = false
        }

        // 因为我们在画布内点击并且绘画，如果鼠标拖到画布外松开，则画布的鼠标抬起事件无法监听到，从而会出现接下来用户不用点击鼠标也可以绘画的bug，所以我们给document加一个mousemove事件，如果鼠标拖到了外面则也把这个isPainting也置为false，不过要注意，别忘了给前面的画布的事件阻止冒泡，否则就有意思了...
        document.onmousemove = (event) => {
            isPainting = false
        }
    </script>
</body>

</html>